<template>
  <div>
    <el-form
      :model="pwdForm"
      :rules="rules"
      ref="pwdForm"
      label-width="80px">
      <!-- <el-form-item
        label="原密码"
        prop="oldPwd">
        <el-input
          placeholder="请输入原密码"
          v-model="pwdForm.oldPwd">
        </el-input>
      </el-form-item> -->
      <el-form-item
        label="新密码"
        prop="newPwd">
        <el-input
          show-password
          placeholder="请输入新密码"
          v-model="pwdForm.newPwd">
        </el-input>
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="reNewPwd">
        <el-input
          show-password
          placeholder="请再次输入新密码"
          v-model="pwdForm.reNewPwd">
        </el-input>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button @click="cancelSubmit">
        取消
      </el-button>
      <el-button type="primary" @click="submitForm('pwdForm')">
        确定
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'InitPwdForm',
  data () {
    return {
      pwdForm: {
        // oldPwd: '',
        newPwd: '',
        reNewPwd: ''
      },
      rules: {
        // oldPwd: [
        //   {required: true, message: '请输入原密码', trigger: 'blur'}
        // ],
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 4, max: 20, message: '长度为4-20个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.pwdForm.reNewPwd !== '') {
                this.$refs.pwdForm.validateField('reNewPwd')
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        reNewPwd: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 4, max: 20, message: '长度为4-20个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.pwdForm.newPwd) {
                callback(new Error('两次输入密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 取消提交
    cancelSubmit () {
      this.$emit('cancel')
    },
    // 提交修改表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleInitPassword()
        } else {
          return false
        }
      })
    },
    handleInitPassword () {
      this.$request.user.initPassword(
        this.pwdForm.newPwd,
        res => {
          this.$emit('submit', res.data)
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    }
  }
}
</script>
